#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os, os.path, sys

import tempfile
import unittest

from potherb import log
from potherb.key import Key
from potherb.scan import ScanContext,ScanSpec,RowInterval,TimeInterval
from potherb.range import Range

class   TestRange_001(unittest.TestCase) :
    def setUp(self) :
        self.store_dir = tempfile.mkdtemp(suffix='.dir', prefix='range_cache_')
        log.debug('store_dir=%s', self.store_dir)
        # setUp()

    def removeDirs(self, dir_name) :
        items = os.listdir(dir_name)
        for item in items :
            dir_item = '%s/%s' % (dir_name, item)
            if os.path.isdir(dir_item) :
                self.removeDirs(dir_item)
            else :
                #log.debug('CONTENT of file %s', dir_item)
                #for line in file(dir_item) :
                #    log.debug('%s', line.strip())
                log.debug('remove file %s', dir_item)
                os.remove(dir_item)
        if os.path.exists(dir_name) :
            log.debug('remove directory %s', dir_name)
            os.removedirs(dir_name)
        # removedirs()

    def tearDown(self) :
        if os.path.exists(self.store_dir) :
            self.removeDirs(self.store_dir)
        # tearDown()

    def testInsert_001(self) :
        tablet = Range('range.test', self.store_dir)

        timestamp = 2000
        for repeat in range(3) :
            for row_key in ('foo', 'bar', 'baz') :
                data = '%s--DATA--%d' % (row_key, timestamp)
                columns = [('cf-A','cq-A', data)]
                tablet.insert(row_key, columns, timestamp)

                timestamp += 1

        count_match_result = 3
        context = ScanContext()
        spec = ScanSpec()
        context.scan_spec = spec
        key_maker = Key()
        for row_key in ('foo', 'bar', 'baz') :
            spec.setRow(row_key)
            scanner = tablet.createScanner(context)
            for key,data in scanner :
                #log.debug('KEY=%s DATA=%s', `key`, `data`)
                key_maker.desemble(key)
                self.assertEqual(row_key, key_maker.row_key)
                count_match_result -= 1
            del scanner

        if count_match_result :
            self.fail('Bad test result count: %d (should be 0)' % count_match_result)

        del tablet
        tablet = None
        # testInsert_001

    # class TestCellCache_001

#######################################################################

if  __name__ == '__main__' :
    #log.setLogPath('/dev/null')
    log.enableDebug()

    unittest.main()
